package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     *  营业额统计 :
     * @param begin  开始时间    2023-04-01
     * @param end   结束时间     2023-04-07
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
         // 1.计算日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin) ; // 2023-04-01
        while(!begin.equals(end)){//  begin!=end 进入 循环,如果相当就不再进入
            begin =  begin.plusDays(1);
            dateList.add(begin) ;
        }

        List<Double> turnoverList = new ArrayList<>();

         //2.遍历日期列表.计算每天的营业额
        for (LocalDate date : dateList) {
            // 3 统计数据 (计算完成订单)
            // 3.1 计算一天的开始和结束
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN); //  2023-04-01+ 00:00:00
            LocalDateTime endTime =LocalDateTime.of(date, LocalTime.MAX);  // 2023-04-01+ 23:59:59.9999999
            // select sum(amount)  from orders where status=5
                            // and  order_time >'2023-04-01 :00:00:00'
                            // and order_time< '2023-04-01 23:59:59.99999'
             // 3.2 统计一天的营业额
            Map<String, Object> param = new HashMap<>();
            param.put("beginTime" ,beginTime);
            param.put("endTime" ,endTime);
            param.put("status" , Orders.COMPLETED); // 已完成
            // 查询当天的营业额
            Double  turnover = orderMapper.sumByMap(param);

            if(turnover==null){
                turnover=0.0;
            }
            turnoverList.add(turnover);
        }
        // 4. 拼接数据反馈
        TurnoverReportVO vo = new TurnoverReportVO();
        vo.setDateList(StringUtils.join(dateList, ","));
        vo.setTurnoverList(StringUtils.join(turnoverList, ","));



        // 集合转字符串   (笨方法不推荐)
//        String all="";
//        for (int i = 0; i <dateList.size() ; i++) {
//
//            if(i==dateList.size()-1){
//                all+=dateList.get(i).toString();
//            }else {
//                all+=dateList.get(i).toString()+",";
//            }
//        }
        return vo;
    }

    /**
     *  用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1) 构建日期列表
        // 1.计算日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin) ; // 2023-04-01
        while(!begin.equals(end)){//  begin!=end 进入 循环,如果相当就不再进入
            begin =  begin.plusDays(1);
            dateList.add(begin) ;
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        //2) 循环遍历日期列表
        for (LocalDate date : dateList) {
            // 2.0 计算一天的开始和结束
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN); //  2023-04-01+ 00:00:00
            LocalDateTime endTime =LocalDateTime.of(date, LocalTime.MAX);  // 2023-04-01+ 23:59:59.9999999
            //2.1)  计算每天新增用户数       select count(*) from user where create_time>=? and  create_time<=?
            Integer  newUser= countByMap(beginTime, endTime);
            //2.2)  计算到当天为止用户总数   select count(*) from user where create_time<=?
            Integer  totalUser =countByMap(null, endTime);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        //3) 拼接返回
        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
    }


    private Integer countByMap(LocalDateTime beginTime, LocalDateTime endTime) {
        Map param1= new HashMap();
        param1.put("beginTime", beginTime);
        param1.put("endTime", endTime);
        return  userMapper.countByMap(param1);
    }



    /**
     * 订单数量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
       // 1) 准备日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin) ; // 2023-04-01
        while(!begin.equals(end)){//  begin!=end 进入 循环,如果相当就不再进入
            begin =  begin.plusDays(1);
            dateList.add(begin) ;
        }
        // 订单数 集合
        List<Integer> orderCountList = new ArrayList<>();
        // 有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
      // 2) 遍历日期
        for (LocalDate date : dateList) {
            // 2.0 计算一天的开始和结束
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN); //  2023-04-01+ 00:00:00
            LocalDateTime endTime =LocalDateTime.of(date, LocalTime.MAX);  // 2023-04-01+ 23:59:59.9999999

            // 2.1) 计算当天的 总订单数  (每天)
            // select count(*) from order where order_time>=? and order_time<=?
            Integer totalOrder = countOrderByMap(beginTime, endTime,null);
            // 2.2) 计算当天的 有效单数
            // select count(*) from order where order_time>=? and order_time<=? and status =
            Integer validOrder = countOrderByMap(beginTime, endTime,Orders.COMPLETED);
            orderCountList.add(totalOrder);
            validOrderCountList.add(validOrder);

        }
        // 3) 遍历集合获取 订单总数
        Integer totalOrderCount =0;
        for (Integer count : orderCountList) {
            totalOrderCount+=count;
        }



        //Integer totalOrderCount = orderCountList.stream().reduce((x,y)->x+y).get();
        //Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        // 4) 遍历集合获取 有效订单数
        Integer validOrderCount=0;
        for (Integer count : validOrderCountList) {
            validOrderCount+=count;
        }

        //5)计算订单完成率
        Double orderCompletionRate  =0.0;
        if(totalOrderCount!=0&&validOrderCount!=0){ // 分母不能为0,
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }
        // 返回数据
        OrderReportVO vo = new OrderReportVO();
        vo.setDateList(StringUtils.join(dateList,","));
        vo.setOrderCountList(StringUtils.join(orderCountList,","));
        vo.setValidOrderCountList(StringUtils.join(validOrderCountList,","));

        vo.setTotalOrderCount(totalOrderCount);
        vo.setValidOrderCount(validOrderCount);
        vo.setOrderCompletionRate(orderCompletionRate);

        return vo;
    }


    private Integer countOrderByMap(LocalDateTime beginTime, LocalDateTime endTime,Integer status) {
        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 销售统计 top10
     * @param begin yyyy-MM-dd :00:00:00
     * @param end   yyyy-MM-dd :00:00:00
     * @return
     */

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 计算 日期边界
        LocalDateTime beginTime =LocalDateTime.of(begin, LocalTime.MIN); //  2023-04-01+ 00:00:00
        LocalDateTime endTime =LocalDateTime.of(end, LocalTime.MAX);  // 2023-04-30+ 23:59:59.9999999
        //1 查询数据库获取 销售top10
//        select  od.name, sum(od.number) as number  from orders o, order_detail od where o.id=od.order_id
//        and o.status =5
//        and order_time >=? and order_time<=?
//        group by  od.name
//        order by  number desc
//        limit 0,10
        List<GoodsSalesDTO> dtos = orderMapper.top10(beginTime, endTime);
        //2 解析数据
        List<String> nameList= new ArrayList<>();
        List<Integer> numberList= new ArrayList<>();
        dtos.forEach(dto -> {
            nameList.add(dto.getName());
          numberList.add(dto.getNumber());
        });

        //
        String collect = StringUtils.join(
         dtos.stream().map(dto -> {
             return  dto.getName();
         }
        ).collect(Collectors.toList()),",");
        //3) 拼接返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
    @Autowired
    private WorkspaceService workspaceService;
    // 生成Excel 响应给前端
    @Override
    public void export(HttpServletResponse response) {
        // 获取开始时间
        // 获取结束时间
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDate begin = LocalDate.now().minusDays(30);
          // 计算日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin) ; // 2023-04-01
        while(!begin.equals(end)){//  begin!=end 进入 循环,如果相当就不再进入
            begin =  begin.plusDays(1);
            dateList.add(begin) ;
        }
        begin=LocalDate.now().minusDays(30); // 重置begin
        // 计算 日期区间内的营业数据 (总)
        LocalDateTime beginTime =LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime =LocalDateTime.of(end,LocalTime.MAX);

        BusinessDataVO dataAll = workspaceService.getBusinessData(beginTime, endTime);
         // 计算每天的 营业数据
        List<BusinessDataVO> everyDayDataList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 计算每天的开始和结束时间
            LocalDateTime beginTime1 =LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime1 =LocalDateTime.of(date,LocalTime.MAX);
            BusinessDataVO everyDayData = workspaceService.getBusinessData(beginTime1, endTime1);
            everyDayDataList.add(everyDayData);
        }
         // 设置表格中的数
        // 读取表格中的数据 : 方式1 不灵活
        // FileInputStream inputStream = new FileInputStream("D:\\code2\\004_work_sky_out\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx");
        // 使用类加载器读取 项目路径下的文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheetAt(0);
            ///设置标题
            sheet.getRow(1).getCell(1).setCellValue(begin.toString()+"到"+end.toString());
            // 设置数据概览
            XSSFRow row3 = sheet.getRow(3);
            row3.getCell(2).setCellValue(dataAll.getTurnover());
            row3.getCell(4).setCellValue(dataAll.getOrderCompletionRate());
            row3.getCell(6).setCellValue(dataAll.getNewUsers());
            XSSFRow row4= sheet.getRow(4);
            row4.getCell(2).setCellValue(dataAll.getValidOrderCount());
            row4.getCell(4).setCellValue(dataAll.getUnitPrice());
            // 设置每天的数据
            for (int i = 0; i < everyDayDataList.size(); i++) {
                BusinessDataVO dataVO = everyDayDataList.get(i);
                LocalDate date = dateList.get(i);
                XSSFRow row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());
            }
            // 使用 response返回 数据到 前端
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
